//
//  CartoonReadingViewController.m
//  Cartoon
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonReadingViewController.h"
#import "CartoonReadingCollectionViewCell.h"
#import "AlreadyReading.h"
#import "CartoonCollectionAlreadReading.h"
#import "CartoonMyDownLoad.h"
@interface CartoonReadingViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,CartoonReadingCollectionCellDelegate>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableDictionary *pictureDic;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *pictureArr;
@property (nonatomic, strong) UIView *myView;

@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UILabel *sliderLabel;

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, strong) UIView *wenhaoView;
@end

@implementation CartoonReadingViewController
//- (void)dealloc
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.pictureArr = [NSMutableArray array];
    
    self.tabBarController.tabBar.hidden = YES;

    
    self.navigationController.navigationBar.frame = CGRectMake(0, 0, SelfViewWidth, 64);
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"wenhao"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction:)];
    
    
    self.wenhaoView = [[UIView alloc] initWithFrame:self.view.bounds];
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(SelfViewWidth / 3, 0, 1, SelfViewHeight)];
    view1.backgroundColor = [UIColor yellowColor];
    [self.wenhaoView addSubview:view1];
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(SelfViewWidth / 3 * 2, 0, 1, SelfViewHeight)];
    view2.backgroundColor = [UIColor yellowColor];
    [self.wenhaoView addSubview:view2];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SelfViewWidth / 3, SelfViewHeight)];
    label1.text = @"上\n一\n页";
    label1.numberOfLines = 0;
    [self.wenhaoView addSubview:label1];
    label1.textColor = [UIColor yellowColor];
    label1.textAlignment = NSTextAlignmentCenter;
    label1.font = [UIFont systemFontOfSize:22];
    
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(SelfViewWidth / 3, 0, SelfViewWidth / 3, SelfViewHeight)];
    label2.text = @"状\n态\n栏";
    label2.numberOfLines = 0;
    [self.wenhaoView addSubview:label2];
    label2.textColor = [UIColor yellowColor];
    label2.textAlignment = NSTextAlignmentCenter;
    label2.font = [UIFont systemFontOfSize:22];
    
    
    UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(SelfViewWidth / 3 * 2, 0, SelfViewWidth / 3, SelfViewHeight)];
    label3.text = @"下\n一\n页";
    label3.numberOfLines = 0;
    [self.wenhaoView addSubview:label3];
    label3.textColor = [UIColor yellowColor];
    label3.textAlignment = NSTextAlignmentCenter;
    label3.font = [UIFont systemFontOfSize:22];
    
    
    UITapGestureRecognizer *tapwenhao = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(wenhaoViewHidden)];
    tapwenhao.numberOfTapsRequired = 1;
    tapwenhao.numberOfTouchesRequired = 1;
    [self.wenhaoView addGestureRecognizer:tapwenhao];
    
    self.wenhaoView.hidden = YES;
    
    [self.view addSubview:_wenhaoView];
    self.wenhaoView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view bringSubviewToFront:_wenhaoView];
    
    
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.itemSize = CGSizeMake(SelfViewWidth, SelfViewHeight);
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, SelfViewWidth, SelfViewHeight - 20) collectionViewLayout:_flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    
//    _collectionView.bounces = NO;
    _collectionView.pagingEnabled = YES;
    
    [_collectionView registerClass:[CartoonReadingCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];
    
    
    
    
    if (_filePictureArray == nil) {
        
        [self readingHandler];
        BOOL result = [[FMDB shareFMDB].db open];
        
        if (result == NO) {
//            NSLog(@"NO == %d",result);
            
        }else{
            
            BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonCollectionAlreadReading (image text primary key, name text , lated_seqno text , comic_id text)"]];
            
//            NSLog(@"创建是否成功 :%d",creatResult);
            
        }
        [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"insert into CartoonCollectionAlreadReading values ('%@','%@','%@','%@')",_cover_url,_bigTitle,_lated_seqno,_comic_id]];

        
    }else{
        self.pictureArr = [NSMutableArray arrayWithArray:self.filePictureArray];
        self.title = self.myTitle;
        [self.collectionView reloadData];
    }
    

    UISlider *lightslider = [[UISlider alloc] initWithFrame:CGRectMake(20, SelfViewHeight / 5 * 3, SelfViewHeight / 5 * 3, 10)];
    float value = [UIScreen mainScreen].brightness;
    lightslider.value = value;
    lightslider.tag = 111;
    lightslider.hidden = YES;
    lightslider.center = CGPointMake(20, SelfViewHeight / 3 + 64);
    lightslider.transform = CGAffineTransformMakeRotation(- M_PI_2);
    lightslider.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    [lightslider addTarget:self action:@selector(lightslider:) forControlEvents:UIControlEventValueChanged];
    lightslider.tintColor = [UIColor whiteColor];
    [self.view addSubview:lightslider];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    image.center = CGPointMake(20, SelfViewHeight / 3 + 64 + SelfViewHeight / 5 * 3 / 2 + 20);
    image.tag = 112;
    image.hidden = YES;
    image.image = [UIImage imageNamed:@"dengpao"];
    [self.view addSubview:image];
    
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    saveButton.frame = CGRectMake(0, 0, 60, 30);
    saveButton.center = CGPointMake(SelfViewWidth - 40, SelfViewHeight / 2 - 30);
    [saveButton setTitle:@"保存图片" forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(saveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    saveButton.tintColor = [UIColor yellowColor];
    saveButton.tag = 113;
    saveButton.hidden = YES;
    saveButton.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    saveButton.layer.cornerRadius = 5;
    [self.view addSubview:saveButton];
    
    
    UIButton *HVButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    HVButton.frame = CGRectMake(0, 0, 60, 30);
    HVButton.center = CGPointMake(SelfViewWidth - 40, SelfViewHeight / 2 + 20);
    [HVButton setTitle:@"上下翻页" forState:UIControlStateNormal];
    HVButton.titleLabel.text = @"上下翻页";
    HVButton.tag = 114;
    [HVButton addTarget:self action:@selector(HVButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    HVButton.tintColor = [UIColor yellowColor];
    HVButton.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    HVButton.layer.cornerRadius = 5;
    HVButton.hidden = YES;
    [self.view addSubview:HVButton];
    
    
    
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, SelfViewHeight - 64, SelfViewWidth, 64)];
    _myView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    [self.view addSubview:_myView];
    UIButton *beforeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    beforeButton.frame = CGRectMake(0, 0, SelfViewWidth / 5, 64);
    [beforeButton setTitle:@"上一话" forState:UIControlStateNormal];
    beforeButton.tintColor = [UIColor whiteColor];
    [beforeButton addTarget:self action:@selector(beforeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    beforeButton.tag = 10001;
    [self.myView addSubview:beforeButton];
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    nextButton.frame = CGRectMake(SelfViewWidth - SelfViewWidth / 5, 0, SelfViewWidth / 5, 64);
    [nextButton setTitle:@"下一话" forState:UIControlStateNormal];
    nextButton.tintColor = [UIColor whiteColor];
    [nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    nextButton.tag = 10002;
    [self.myView addSubview:nextButton];
    
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(SelfViewWidth / 5, self.myView.frame.size.height / 2 - 10, SelfViewWidth / 5 * 3, 20)];
//    _slider.backgroundColor = [UIColor whiteColor];
    self.slider.maximumValue = 1;
    self.slider.minimumValue = 1;
    [_slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
    [self.myView addSubview:_slider];
    
    self.sliderLabel = [[UILabel alloc] initWithFrame:CGRectMake(SelfViewWidth / 2 - 40, self.myView.frame.size.height - 30, 80, 20)];
    self.sliderLabel.text = @"1/1";
    _sliderLabel.textColor = [UIColor whiteColor];
    _sliderLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.myView addSubview:_sliderLabel];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(collectionTopAction:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tap];
    
    [UIView animateWithDuration:0.5 animations:^{
        if (self.navigationController.navigationBar.frame.origin.y == 0) {
            self.navigationController.navigationBar.frame = CGRectMake(0, -64, SelfViewWidth, 64);
            self.myView.frame = CGRectMake(0, SelfViewHeight, SelfViewWidth, 64);
            
        }else{
            self.navigationController.navigationBar.frame = CGRectMake(0, 0, SelfViewWidth, 64);
            self.myView.frame = CGRectMake(0, SelfViewHeight - 64, SelfViewWidth, 64);
            
        }
    } completion:^(BOOL finished) {
        
        [self.collectionView reloadData];
        
    }];
    
    
    // 监测手机横屏状态
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
//    
//    
//    [[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceOrientationDidChangeNotification object:nil];
//    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeWindowTransform" object:@"YES"];
    
}
- (void)wenhaoViewHidden
{
    self.wenhaoView.hidden = YES;
}
- (void)rightButtonAction:(UIBarButtonItem *)item
{
    self.wenhaoView.hidden = NO;
    [self.view bringSubviewToFront:_wenhaoView];
    
    [self passValue:nil point:self.view.center];
}
- (void)orientChange:(NSNotification *)noti
{
    NSLog(@"切换横屏");
    NSDictionary* ntfDict = [noti userInfo];
    //判断横屏
    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;
    /*
     UIDeviceOrientationUnknown,
     UIDeviceOrientationPortrait,            // Device oriented vertically, home button on the bottom
     UIDeviceOrientationPortraitUpsideDown,  // Device oriented vertically, home button on the top
     UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right
     UIDeviceOrientationLandscapeRight,      // Device oriented horizontally, home button on the left
     UIDeviceOrientationFaceUp,              // Device oriented flat, face up
     UIDeviceOrientationFaceDown             // Device oriented flat, face down   */
    
    switch (orient)
    {
        case UIDeviceOrientationPortrait:
//            self.collectionView.frame = CGRectMake( 0, 0, SelfViewWidth, SelfViewHeight - 20);
//            [self.collectionView reloadData];
            
            break;
        case UIDeviceOrientationLandscapeLeft:

//            self.collectionView.frame = CGRectMake( 0, 0, SelfViewWidth - 200, SelfViewHeight);
//            [self.view reloadInputViews];
//            [self.collectionView reloadData];
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            
            
            break;
        case UIDeviceOrientationLandscapeRight:
       
//             self.collectionView.frame = CGRectMake( 0, 0, SelfViewWidth, SelfViewHeight);
//            [self.collectionView reloadData];
            break;
            
        default:
            break;
    }
}

- (void)HVButtonAction:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"上下翻页"]) {
        [btn setTitle:@"左右翻页" forState:UIControlStateNormal];
        btn.titleLabel.text = @"左右翻页";
        self.flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentOffset.x / SelfViewWidth * (SelfViewHeight - 20));
    }else{
        [btn setTitle:@"上下翻页" forState:UIControlStateNormal];
        btn.titleLabel.text = @"上下翻页";
        self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.y / (SelfViewHeight - 20) * SelfViewWidth, 0);
    }
}
- (void)saveButtonAction:(UIButton *)btn
{
    NSInteger page = self.collectionView.contentOffset.x / SelfViewWidth;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    if (self.pictureArr.count > 0) {
        if (_filePictureArray == nil) {
            [imageView sd_setImageWithURL:[NSURL URLWithString:[self.pictureArr objectAtIndex:page]]];
            
        }else{
            
            imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",_path,_filePictureArray[page]]];
        }
    }
    UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error == nil) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [alert show];
        
    }else{
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [alert show];
    }
}
- (void)nextButtonAction:(UIButton *)btn
{
//    [btn removeTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    btn.userInteractionEnabled = NO;
    if (self.page != 0) {
    
    
    [self.pictureArr removeAllObjects];
    if (_filePictureArray == nil) {
        self.page --;
        [self readingHandler];
        
    }else{

        self.page ++;
        NSInteger i = 0;
        for (NSString *str in _pageArray) {
            if (self.page == [str integerValue]) {
                i++;
                CartoonMyDownLoad *down = [self.dataDic objectForKey:[NSString stringWithFormat:@"%ld",self.page]];
                NSString *strr = [NSString stringWithFormat:@"%@%@",[[down.cartoonID componentsSeparatedByString:@"/"] firstObject],[[down.cartoonID componentsSeparatedByString:@"/"] lastObject]];
//                NSLog(@"%@",strr);
                //初始化Documents路径
                NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
                //初始化临时文件路径
                NSString *folderPath = [path stringByAppendingPathComponent:strr];
                //创建文件管理器
                NSFileManager *fileManager = [NSFileManager defaultManager];
                //判断temp文件夹是否存在
                BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
                if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
                    [fileManager createDirectoryAtPath:folderPath
                           withIntermediateDirectories:YES
                                            attributes:nil
                                                 error:nil];
                }
                //    NSLog(@"%@",myPath);
                NSArray *arr = [fileManager directoryContentsAtPath:folderPath];
                NSMutableArray *array = [NSMutableArray array];
                for (NSString *str in arr) {
                    if ([[[str componentsSeparatedByString:@"."] lastObject] isEqualToString:@"jpg"]) {
                        [array addObject:str];
                    }
                }
                NSLog(@"%@",array);
                self.path = folderPath;
                self.filePictureArray = [NSMutableArray arrayWithArray:array];
                self.pictureArr = [NSMutableArray arrayWithArray:array];
                self.collectionView.contentOffset = CGPointMake(0, 0);
                [self.collectionView reloadData];
                btn.userInteractionEnabled = YES;

            }
        }
        if (i == 0) {
            btn.userInteractionEnabled = YES;
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您没有加载下一章节" delegate:self cancelButtonTitle:nil otherButtonTitles:@"返回", nil];
            [alertView show];
        }
    }
    }else{
        btn.userInteractionEnabled = YES;
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您已读至最新章节" delegate:self cancelButtonTitle:nil otherButtonTitles:@"返回", nil];
        [alertView show];
    }
}
- (void)beforeButtonAction:(UIButton *)btn
{

//    [btn removeTarget:self action:@selector(beforeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    btn.userInteractionEnabled = NO;
    if (self.page != [_lated_seqno integerValue] - 1) {
    
    self.collectionView.contentOffset = CGPointMake(0, 0);
    [self.pictureArr removeAllObjects];
    if (_filePictureArray == nil) {
        self.page ++;
        [self readingHandler];
        
    }else{
//        self.pictureArr = [NSMutableArray arrayWithArray:self.filePictureArray];
//        self.title = self.myTitle;
//        [self.collectionView reloadData];
////        [btn addTarget:self action:@selector(beforeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//        btn.userInteractionEnabled = YES;
        self.page --;
        NSInteger i = 0;
        for (NSString *str in _pageArray) {
            if (self.page == [str integerValue]) {
                i++;

        CartoonMyDownLoad *down = [self.dataDic objectForKey:[NSString stringWithFormat:@"%ld",self.page]];
        NSString *strr = [NSString stringWithFormat:@"%@%@",[[down.cartoonID componentsSeparatedByString:@"/"] firstObject],[[down.cartoonID componentsSeparatedByString:@"/"] lastObject]];
//        NSLog(@"%@",strr);
        //初始化Documents路径
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
        //初始化临时文件路径
        NSString *folderPath = [path stringByAppendingPathComponent:strr];
        //创建文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //判断temp文件夹是否存在
        BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
        if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
            [fileManager createDirectoryAtPath:folderPath
                   withIntermediateDirectories:YES
                                    attributes:nil
                                         error:nil];
        }
        //    NSLog(@"%@",myPath);
        NSArray *arr = [fileManager directoryContentsAtPath:folderPath];
        NSMutableArray *array = [NSMutableArray array];
        for (NSString *str in arr) {
            if ([[[str componentsSeparatedByString:@"."] lastObject] isEqualToString:@"jpg"]) {
                [array addObject:str];
            }
        }
//        NSLog(@"%@",array);
        self.path = folderPath;
        self.filePictureArray = [NSMutableArray arrayWithArray:array];
        self.pictureArr = [NSMutableArray arrayWithArray:array];

        self.collectionView.contentOffset = CGPointMake(0, 0);
                
        [self.collectionView reloadData];
        btn.userInteractionEnabled = YES;
            }
        }
        if (i == 0) {
            btn.userInteractionEnabled = YES;
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您没有加载下一章节" delegate:self cancelButtonTitle:nil otherButtonTitles:@"返回", nil];
            [alertView show];
        }
    }
    }else{
        btn.userInteractionEnabled = YES;
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前为第一章节" delegate:self cancelButtonTitle:nil otherButtonTitles:@"返回", nil];
        [alertView show];
    }
}
- (void)lightslider:(UISlider *)slider
{
    [[UIScreen mainScreen] setBrightness:slider.value];
}
- (void)sliderChange:(UISlider *)slider
{
    // slider的值   范围在 0 到 1
    NSInteger page = slider.value / 1;
    self.slider.value = page;
    NSInteger max = self.slider.maximumValue / 1;
    self.sliderLabel.text = [NSString stringWithFormat:@"%ld/%ld",page,max];
    self.collectionView.contentOffset = CGPointMake((_slider.value - 1) * SelfViewWidth, 0);
//    NSLog(@"%f",_slider.value);
}

- (void)collectionTopAction:(UIGestureRecognizer *)tap
{
    
    CGPoint point = [tap locationInView:self.view];
//    NSLog(@"view %f,%f",point.x,point.y);
    if (point.y > SelfViewHeight - 64 && !self.myView.hidden) {
        
    }else{
    [self passValue:tap point:point];
    }
}
- (void)leftButtonAction:(UINavigationItem *)item
{
    self.tabBarController.tabBar.hidden = NO;
    self.myView.hidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController.navigationBar setHidden:NO];
}
- (void)readingHandler
{
    BOOL result = [[FMDB shareFMDB].db open];
    
    if (result == NO) {
        NSLog(@"NO == %d",result);
        
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table AlreadyReading (cartoonID text primary key, cartoonPage text)"]];
        
        NSLog(@"创建是否成功 :%d",creatResult);
        
    }
    
//    CartoonReadingViewController *reading = [[CartoonReadingViewController alloc] init];
//    reading.page = indexPath.item;
//    CartoonDetailsModel *model = [self.dataArr objectAtIndex:0];
//    reading.comic_id = model.comic_id;
//    reading.cover_url = model.cover_url;
//    reading.bigTitle = model.title;
//    reading.lated_seqno = model.lated_seqno;
    
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
    NSMutableArray *array = [NSMutableArray array];
    
    while ([set next]) {
        
        AlreadyReading *read = [[AlreadyReading alloc]init];
        read.cartoonID = [set stringForColumn:@"cartoonID"];
        read.cartoonPage = [set stringForColumn:@"cartoonPage"];
        if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:_comic_id]) {
            [array addObject:read];
            break;
        }
    }
    
    if (array.count > 0) {
        AlreadyReading *read = array[0];
        if ([_lated_seqno integerValue] - _page == [[[read.cartoonID componentsSeparatedByString:@"/"] firstObject] integerValue]) {
            [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonID = '%@' where cartoonID = '%@' and cartoonPage = '%@'",[NSString stringWithFormat:@"%ld/%@",[_lated_seqno integerValue] - _page,_comic_id],read.cartoonID,read.cartoonPage]];
        }else{
            [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonID = '%@' where cartoonID = '%@' and cartoonPage = '%@'",[NSString stringWithFormat:@"%ld/%@",[_lated_seqno integerValue] - _page,_comic_id],read.cartoonID,read.cartoonPage]];
            [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonPage = '%@' where cartoonID = '%@' and cartoonPage = '%@'",@"1",[NSString stringWithFormat:@"%ld/%@",[_lated_seqno integerValue] - _page,_comic_id],read.cartoonPage]];
        }
        
    }else{
//        NSLog(@"%@",[NSString stringWithFormat:@"%@/%@",[NSString stringWithFormat:@"%ld",[_lated_seqno integerValue] - _page],_comic_id]);
        BOOL insertResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"insert into AlreadyReading values ('%@','%@')",[NSString stringWithFormat:@"%@/%@",[NSString stringWithFormat:@"%ld",[_lated_seqno integerValue] - _page],_comic_id],@"1"]];
        if (insertResult == YES) {
            NSLog(@"插入成功");
        }else{
            NSLog(@"插入失败");
        }
    }
    
    NSString *str = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/comicChapterListForIosV2/uin/0/local_version/3.1.0/channel/1001/guest_id/491A80FA-091B-4330-B939-7DE39BB24F7F/comic_id/%@",self.comic_id];
    [NetHandler nilHUDdataWithUrl:str complant:^(id data) {
        self.dataArray = [data objectForKey:@"data"];
        self.pictureDic = [self.dataArray objectAtIndex:self.page];
        self.title = [self.pictureDic objectForKey:@"title"];
        [self handler];
    }];
}
- (void)handler
{
    NSString *str = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/chapterPictureListForIos/comic_id/%@/cid/%@/clientType/0",self.comic_id,[self.pictureDic objectForKey:@"cid"]];
    [NetHandler nilHUDdataWithUrl:str complant:^(id data) {
        for (NSDictionary *dic in [[data objectForKey:@"data"] objectForKey:@"img_infos"]) {
            [self.pictureArr addObject:[dic objectForKey:@"current_img_url"]];
//            [(UIButton *)[self.myView viewWithTag:10001] addTarget:self action:@selector(beforeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//            [(UIButton *)[self.myView viewWithTag:10002] addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            if (![self.myView viewWithTag:10001].userInteractionEnabled) {
                self.collectionView.contentOffset = CGPointMake(0, 0);
            }
            
            [self.myView viewWithTag:10001].userInteractionEnabled = YES;
            [self.myView viewWithTag:10002].userInteractionEnabled = YES;
            
            [self.collectionView reloadData];
        }
    }];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{

    if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionVertical) {
        if (scrollView.contentOffset.y < 0 || scrollView.contentOffset.y > (SelfViewHeight - 20) * (_pictureArr.count - 1)) {
            
            
            if (scrollView.contentOffset.y < 0) {
                if ([self.myView viewWithTag:10001].userInteractionEnabled) {
                    
                    [self beforeButtonAction:(UIButton *)[self.myView viewWithTag:10001]];
                }
            }else if (scrollView.contentOffset.y > (SelfViewHeight - 20) * (_pictureArr.count - 1)){
                if ([self.myView viewWithTag:10002].userInteractionEnabled) {
                    
                    [self nextButtonAction:(UIButton *)[self.myView viewWithTag:10002]];
                }
            }else{
                NSInteger page = scrollView.contentOffset.y / (SelfViewHeight - 20) + 1;
                self.slider.value = page;
                NSInteger max = self.slider.maximumValue / 1;
                self.sliderLabel.text = [NSString stringWithFormat:@"%ld/%ld",page,max];
                
                if (self.pictureArr.count > 0) {
                    
                    
                    [[FMDB shareFMDB].db open];
                    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
                    NSMutableArray *array = [NSMutableArray array];
                    
                    while ([set next]) {
                        
                        AlreadyReading *read = [[AlreadyReading alloc]init];
                        read.cartoonID = [set stringForColumn:@"cartoonID"];
                        read.cartoonPage = [set stringForColumn:@"cartoonPage"];
                        if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.comic_id]) {
                            [array addObject:read];
                            break;
                        }
                    }
                    if (array.count > 0) {
                        
                        AlreadyReading *read = array[0];
                        [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonPage = '%@' where cartoonID = '%@' and cartoonPage = '%@'",[NSString stringWithFormat:@"%ld",page],read.cartoonID,read.cartoonPage]];
                    }
                }
                
            }}
    }else
        if(self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal){
            if (scrollView.contentOffset.x < 0 || scrollView.contentOffset.x > SelfViewWidth * (_pictureArr.count - 1)) {
                if (scrollView.contentOffset.x < 0) {
                    if ([self.myView viewWithTag:10001].userInteractionEnabled) {
                        
                        [self beforeButtonAction:(UIButton *)[self.myView viewWithTag:10001]];
                    }
                }else if (scrollView.contentOffset.x > SelfViewWidth * (_pictureArr.count - 1)){
                    if ([self.myView viewWithTag:10002].userInteractionEnabled) {
                        
                        [self nextButtonAction:(UIButton *)[self.myView viewWithTag:10002]];
                    }
                }else{
                    NSInteger page = scrollView.contentOffset.x / SelfViewWidth + 1;
                    self.slider.value = page;
                    NSInteger max = self.slider.maximumValue / 1;
                    self.sliderLabel.text = [NSString stringWithFormat:@"%ld/%ld",page,max];
                    
                    if (self.pictureArr.count > 0) {
                        
                        
                        [[FMDB shareFMDB].db open];
                        FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
                        NSMutableArray *array = [NSMutableArray array];
                        
                        while ([set next]) {
                            
                            AlreadyReading *read = [[AlreadyReading alloc]init];
                            read.cartoonID = [set stringForColumn:@"cartoonID"];
                            read.cartoonPage = [set stringForColumn:@"cartoonPage"];
                            if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.comic_id]) {
                                [array addObject:read];
                                break;
                            }
                        }
                        
                        //        NSLog(@"%@",[NSString stringWithFormat:@"%ld/%@",self.page,self.comic_id]);
                        if (array.count > 0) {
                            
                            AlreadyReading *read = array[0];
                            [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonPage = '%@' where cartoonID = '%@' and cartoonPage = '%@'",[NSString stringWithFormat:@"%ld",page],read.cartoonID,read.cartoonPage]];
                            
                        }
                    }
                }
            }
        }

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    
    if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionVertical) {
        if (scrollView.contentOffset.y > 0 && scrollView.contentOffset.y < (SelfViewHeight - 20) * (_pictureArr.count - 1)) {
            
        
        if (scrollView.contentOffset.y < 0) {
            if ([self.myView viewWithTag:10001].userInteractionEnabled) {
                
                [self beforeButtonAction:(UIButton *)[self.myView viewWithTag:10001]];
            }
        }else if (scrollView.contentOffset.y > (SelfViewHeight - 20) * (_pictureArr.count - 1)){
            if ([self.myView viewWithTag:10002].userInteractionEnabled) {
                
                [self nextButtonAction:(UIButton *)[self.myView viewWithTag:10002]];
            }
        }else{
            NSInteger page = scrollView.contentOffset.y / (SelfViewHeight - 20) + 1;
            self.slider.value = page;
            NSInteger max = self.slider.maximumValue / 1;
            self.sliderLabel.text = [NSString stringWithFormat:@"%ld/%ld",page,max];
            
            if (self.pictureArr.count > 0) {
                
                
                [[FMDB shareFMDB].db open];
                FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
                NSMutableArray *array = [NSMutableArray array];
                
                while ([set next]) {
                    
                    AlreadyReading *read = [[AlreadyReading alloc]init];
                    read.cartoonID = [set stringForColumn:@"cartoonID"];
                    read.cartoonPage = [set stringForColumn:@"cartoonPage"];
                    if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.comic_id]) {
                        [array addObject:read];
                        break;
                    }
                }
                if (array.count > 0) {
                    
                    AlreadyReading *read = array[0];
                    [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonPage = '%@' where cartoonID = '%@' and cartoonPage = '%@'",[NSString stringWithFormat:@"%ld",page],read.cartoonID,read.cartoonPage]];
                }
            }
            
        }}
    }else
        if(self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal){
            if (scrollView.contentOffset.x > 0 && scrollView.contentOffset.x <= SelfViewWidth * (_pictureArr.count - 1)) {
            if (scrollView.contentOffset.x < 0) {
                if ([self.myView viewWithTag:10001].userInteractionEnabled) {
                    
                    [self beforeButtonAction:(UIButton *)[self.myView viewWithTag:10001]];
                }
            }else if (scrollView.contentOffset.x > SelfViewWidth * (_pictureArr.count - 1)){
                if ([self.myView viewWithTag:10002].userInteractionEnabled) {
                    
                    [self nextButtonAction:(UIButton *)[self.myView viewWithTag:10002]];
                }
            }else{
                NSInteger page = scrollView.contentOffset.x / SelfViewWidth + 1;
                self.slider.value = page;
                NSInteger max = self.slider.maximumValue / 1;
                self.sliderLabel.text = [NSString stringWithFormat:@"%ld/%ld",page,max];
                
                if (self.pictureArr.count > 0) {
                    
                    
                    [[FMDB shareFMDB].db open];
                    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
                    NSMutableArray *array = [NSMutableArray array];
                    
                    while ([set next]) {
                        
                        AlreadyReading *read = [[AlreadyReading alloc]init];
                        read.cartoonID = [set stringForColumn:@"cartoonID"];
                        read.cartoonPage = [set stringForColumn:@"cartoonPage"];
                        if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.comic_id]) {
                            [array addObject:read];
                            break;
                        }
                    }
                    
                    //        NSLog(@"%@",[NSString stringWithFormat:@"%ld/%@",self.page,self.comic_id]);
                    if (array.count > 0) {
                        
                        AlreadyReading *read = array[0];
                        [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update AlreadyReading set cartoonPage = '%@' where cartoonID = '%@' and cartoonPage = '%@'",[NSString stringWithFormat:@"%ld",page],read.cartoonID,read.cartoonPage]];
                        
                    }
                }
            }
            }
        }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    
    [[FMDB shareFMDB].db open];
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM AlreadyReading"];
    NSMutableArray *array = [NSMutableArray array];
    
    while ([set next]) {
        
        AlreadyReading *read = [[AlreadyReading alloc]init];
        read.cartoonID = [set stringForColumn:@"cartoonID"];
        read.cartoonPage = [set stringForColumn:@"cartoonPage"];
        if ([[[read.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.comic_id]) {
            [array addObject:read];
            break;
        }
    }
    if (array.count > 0) {
        
    
    AlreadyReading *read = array[0];
    self.collectionView.contentOffset = CGPointMake(([read.cartoonPage integerValue] - 1) * SelfViewWidth, 0);
    }
    if (self.pictureArr.count > 0) {
        self.slider.maximumValue = self.pictureArr.count;
        NSInteger page = (self.collectionView.contentOffset.x / SelfViewWidth + 1) / 1;
        self.slider.value = page;
        NSInteger max = self.slider.maximumValue / 1;
        self.sliderLabel.text = [NSString stringWithFormat:@"%ld/%ld",page,max];
    }

    
    return self.pictureArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CartoonReadingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.myScrollView.zoomScale = 1.0;
    if (self.pictureArr.count > 0) {
        if (_filePictureArray == nil) {
            [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:[self.pictureArr objectAtIndex:indexPath.item]] placeholderImage:[UIImage imageNamed:@"5"]];
            if (indexPath.item != self.pictureArr.count - 1) {
                CartoonReadingCollectionViewCell *nextCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:[NSIndexPath indexPathForItem:indexPath.item + 1 inSection:0]];
                
        
                [nextCell.myImageView sd_setImageWithURL:[NSURL URLWithString:[self.pictureArr objectAtIndex:indexPath.item + 1]]];
            }
            
        }else{
            
            cell.myImageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",_path,_filePictureArray[indexPath.item]]];
        }
      
    }
    
    cell.delegate = self;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"点击事件");
//    NSLog(@"%f",self.navigationController.view.frame.origin.y);
//    self.navigationController.view.frame = CGRectMake(0, - 64, SelfViewWidth, SelfViewHeight);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
        CGSize size = CGSizeMake(SelfViewWidth, SelfViewHeight - 20);
        return size;
 
}
- (void)passValue:(id)user point:(CGPoint)point
{
    
    if ((point.x > SelfViewWidth / 3 && point.x < SelfViewWidth / 3 * 2) || self.pictureArr.count == 0) {
        
        [UIView animateWithDuration:0.5 animations:^{
            if (self.navigationController.navigationBar.frame.origin.y == 0) {
                self.navigationController.navigationBar.frame = CGRectMake(0, -64, SelfViewWidth, 64);
                self.myView.frame = CGRectMake(0, SelfViewHeight, SelfViewWidth, 64);
                float value = [UIScreen mainScreen].brightness;
                UISlider *light = (UISlider *)[self.view viewWithTag:111];
                light.hidden = YES;
                light.value = value;
                UIImageView *imageView = (UIImageView *)[self.view viewWithTag:112];
                imageView.hidden = YES;
                
                [self.view viewWithTag:113].hidden = YES;
                [self.view viewWithTag:114].hidden = YES;
            }else{
                self.navigationController.navigationBar.frame = CGRectMake(0, 0, SelfViewWidth, 64);
                self.myView.frame = CGRectMake(0, SelfViewHeight - 64, SelfViewWidth, 64);
                float value = [UIScreen mainScreen].brightness;
                UISlider *light = (UISlider *)[self.view viewWithTag:111];
                light.hidden = NO;
                light.value = value;
                UIImageView *imageView = (UIImageView *)[self.view viewWithTag:112];
                imageView.hidden = NO;
                [self.view viewWithTag:113].hidden = NO;
                [self.view viewWithTag:114].hidden = NO;
            }
        } completion:^(BOOL finished) {
            
//            [self.collectionView reloadData];
            
        }];
    }
    else if (point.x < SelfViewWidth / 3 && self.pictureArr.count > 0) {
        if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
            if (self.collectionView.contentOffset.x == 0) {
                
                if ([self.myView viewWithTag:10001].userInteractionEnabled) {
                    
                    [self beforeButtonAction:(UIButton *)[self.myView viewWithTag:10001]];
                }
            }else if(self.collectionView.contentOffset.x != 0){
                self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x - SelfViewWidth, 0);
            }
        }else if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionVertical){
            if (self.collectionView.contentOffset.y == 0) {
                
                if ([self.myView viewWithTag:10001].userInteractionEnabled) {
                    
                    [self beforeButtonAction:(UIButton *)[self.myView viewWithTag:10001]];
                }
            }else if(self.collectionView.contentOffset.y != 0){
                self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentOffset.y - (SelfViewHeight - 20));
            }
        }

    }else if (point.x > SelfViewWidth / 3 * 2  && self.pictureArr.count > 0){
        if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
            if (self.collectionView.contentOffset.x == SelfViewWidth * (_pictureArr.count - 1)){
                
                if ([self.myView viewWithTag:10002].userInteractionEnabled) {
                    
                    [self nextButtonAction:(UIButton *)[self.myView viewWithTag:10002]];
                }
            }else if(self.collectionView.contentOffset.x != SelfViewWidth * (_pictureArr.count - 1)){
                self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x + SelfViewWidth, 0);
            }

            
        }else if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionVertical){
                if (self.collectionView.contentOffset.y == (SelfViewHeight - 20) * (_pictureArr.count - 1)){
                    
                    if ([self.myView viewWithTag:10002].userInteractionEnabled) {
                        
                        [self nextButtonAction:(UIButton *)[self.myView viewWithTag:10002]];
                    }
                }else if(self.collectionView.contentOffset.y != (SelfViewHeight - 20) * (_pictureArr.count - 1)){
                    self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentOffset.y + (SelfViewHeight - 20));
                }

        }
            }


    
}
- (void)viewWillDisappear:(BOOL)animated
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeWindowTransform" object:@"NO"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
